//
//  RHLocalDevSystemVC.m
//  RuiHeAppApp
//
//  Created by Yan Chen on 2024/3/26.
//

#import "RHLocalDevSystemVC.h"
#import "RHLocalDevTopoCell.h"
#import "RHDeviceTopoCell.h"
#import "RHLocalEnergyStorageStatusCell.h"
#import "RHLocalDeviceSetCell.h"
#import "RHLocalBatteryDetailVC.h"
#import "RHLocalConfigOptionVC.h"
#import "RHLocalFirmwareListVC.h"
#import "CBLECenterMnger.h"
#import "RHBleCmdData.h"
#import "RHLocalEnergyFullVC.h"
#import "CBLEDataParse.h"
#import "RHBleCmdManager.h"
#import "RHLocalPackVC.h"

@interface RHLocalDevSystemVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSArray *titleArr;

@property (nonatomic ,strong) NSMutableDictionary *topoDataDic;

@end

@implementation RHLocalDevSystemVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = UIColor.clearColor;
    [self setupUI];
    [self createCmd];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getDeviceInfo];
    });
   
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.recieveMsg = YES;
}



- (void)setupUI{
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_ACK,receiveDeviceMsg:);
    ADD_MESSAGE(BLEMSG_PHERAL_SENDMSG_FINISH,sendCmdFinish);
    self.titleArr = @[@"",@"",@""];
    self.topoDataDic = [NSMutableDictionary dictionary];
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.backgroundColor = UIColor.clearColor;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHLocalDevTopoCell class] forCellReuseIdentifier:@"RHLocalDevTopoCell_HE"];
    [_tableView registerClass:[RHLocalEnergyStorageStatusCell class] forCellReuseIdentifier:@"RHEnergyStorageStatusCell_BLE"];
    [_tableView registerClass:[RHLocalDeviceSetCell class] forCellReuseIdentifier:@"RHLocalDeviceSetCell"];
    [self.view addSubview:_tableView];
    
    CGFloat edge = 0;
    if (@available(iOS 13.0, *)) {
        
    }else{
        edge = 25;
    }
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, edge, 0);
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    kWeakSelf;
    [_tableView addHeaderRefresh:^{
        [weakSelf getDeviceInfo];
    }];
    
    _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    if (@available(iOS 13.0, *)) {
        _tableView.automaticallyAdjustsScrollIndicatorInsets = NO;
    }
    
}

-(void)createCmd
{
    NSArray *cmdArr = @[@{
        @"field":@"Ems_PvPwr",
        @"regAddr":@(200),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_GridPwr",
        @"regAddr":@(203),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"dataType":@"signed",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_LoadPwr",
        @"regAddr":@(204),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_BatPwr",
        @"regAddr":@(205),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"dataType":@"signed",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_BatSoc",
        @"regAddr":@(206),
        @"bitWidth":@(16),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_BDE_Day",
        @"comment":@"今日放电量",
        @"regAddr":@(284),
        @"bitWidth":@(32),
        @"ratio":@"0.1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_ChgTim",
        @"comment":@"电池预计充满时间",
        @"regAddr":@(160),
        @"bitWidth":@(32),
        @"ratio":@"1",
        @"cmdType":@(LocalSettingType_EMS)
    },@{
        @"field":@"Ems_DischgTim",
        @"comment":@"电池预计放电时间",
        @"regAddr":@(162),
        @"bitWidth":@(32),
        @"ratio":@"1",
        @"cmdType":@(LocalSettingType_EMS)
    }];
    /*
     ,@{
         @"field":@"Mtr_ubBatSt3401",
         @"comment":@"电池运行状态",
         @"regAddr":@(34),
         @"bitWidth":@(2),
         @"isBit":@(1),
         @"offset":@(0),
         @"cmdType":@(LocalSettingType_Master)
     }
     
     */
    NSMutableArray *mtbArr = [NSMutableArray array];
    [cmdArr enumerateObjectsUsingBlock:^(NSDictionary  *_Nonnull dic, NSUInteger idx, BOOL * _Nonnull stop) {
        RHLocalSettingModel *settingModel = [RHLocalSettingModel yy_modelWithJSON:dic];
        [mtbArr addObject:settingModel];
    }];
    self.cmdArray = mtbArr.copy;
}

-(void)getDeviceInfo
{
    [[RHBleCmdManager shareMnger] readDeviceInfoFromBle:self.cmdArray];
}

-(void)receiveDeviceMsg:(NSNotification *)no
{
    if(!self.recieveMsg)return;
    NSDictionary *dic = [no object];
    //消息是读还是写回复
    int answerType = [dic[CMD_CODE] intValue];
    if(answerType == 0x03){
        NSLog(@"------>收到设备信息:%@",dic);
        //读回复
        [self.cmdArray enumerateObjectsUsingBlock:^(RHLocalSettingModel * _Nonnull obj, NSUInteger index, BOOL * _Nonnull stop) {
            if(obj.regAddr == [dic[CMD_ADDRESS] integerValue]){
                
                NSData *data = dic[CMD_ADDRESS_VALUE];
                NSString *parse_content = [CBLEDataParse parseData:data settingModel:obj];
                NSLog(@"---->%@ = %@",obj.field,parse_content);
                
                [self.topoDataDic setObject:parse_content forKey:obj.field];
            }
            
        }];
        
        [self.tableView reloadData];
    }
     
    
}

-(void)sendCmdFinish
{
    if (self.recieveMsg == NO) {
        return;
    }
    //测试
//    self.topoDataDic = @{
//        @"Ems_GridPwr":@"0",
//        @"Ems_PvPwr":@"0",
//        @"Ems_LoadPwr":@"3"
//    }.mutableCopy;
    
    NSLog(@"------>读取到的设备数据:%@",self.topoDataDic);
    [self.tableView endHeaderRefresh];
    [self.tableView reloadData];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.titleArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 10)];
    if(section == 0){
        headView.backgroundColor = UIColor.clearColor;
    }else{
        headView.backgroundColor = CFTabViewBgColor;
    }
    return headView;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    
    return nil;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(indexPath.section == 0){
        //topo  能量(当日供电)
        RHLocalDevTopoCell *topoCell = [tableView dequeueReusableCellWithIdentifier:@"RHLocalDevTopoCell_HE"];
        topoCell.selectionStyle = UITableViewCellSelectionStyleNone;
        topoCell.topoDataDic = self.topoDataDic;
        kWeakSelf;
        topoCell.chartAction = ^{
            weakSelf.recieveMsg = NO;
            //能量实时曲线
            RHLocalEnergyFullVC *energyVC = [[RHLocalEnergyFullVC alloc]init];
            [weakSelf.navigationController pushViewController:energyVC animated:NO];
        };
        return topoCell;
    }else if(indexPath.section == 1){
        kWeakSelf;
        RHLocalEnergyStorageStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHEnergyStorageStatusCell_BLE"];
        cell.dic = self.topoDataDic;
        cell.detailBlock = ^{
            //没有主控直接跳到pack页面
            if ([CBLECenterMnger shareMnger].curPheral.hasMaster == NO) {
                RHLocalPackVC *vc = [[RHLocalPackVC alloc] init];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            }else{
                RHLocalBatteryDetailVC *chartVC = [[RHLocalBatteryDetailVC alloc]init];
                chartVC.title = @"电池详情".rh_localized;
                [weakSelf.navigationController pushViewController:chartVC animated:YES];
            }
            
        };
        return cell;
    }else if (indexPath.section == 2){
        RHLocalDeviceSetCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHLocalDeviceSetCell"];
        
        //运行配置
        kWeakSelf;
        cell.paraSetBlock = ^{
            RHLocalConfigOptionVC *configVC = [[RHLocalConfigOptionVC alloc]init];
            [weakSelf.navigationController pushViewController:configVC animated:YES];
        };
        //固件升级
        cell.firmwareBlock = ^{
            [QMUITips showInfo:@"暂不支持".rh_localized];
            return;
            RHLocalFirmwareListVC *firmVC = [[RHLocalFirmwareListVC alloc]init];
            [weakSelf.navigationController pushViewController:firmVC animated:YES];
        };
        
        return cell;;
    }
    return [UITableViewCell new];;
}

-(void)dealloc
{
    [[CBLECenterMnger shareMnger] cmdDisconnectCurPheral];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}

#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}
@end
